'use client'

import { useEffect, useState } from 'react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { Loader2, Search as SearchIcon, X } from 'lucide-react';

import { useStore } from "~/core/store";
import { Button } from '~/components/ui/button';
import { Input } from '~/components/ui/input';

type SessionSearchResult = {
  session_id: string;
  matched_message: string;
  created_at: string;
  updated_at: string;
};

export function SearchDialog({
  open,
  onClose
}: {
  open: boolean;
  onClose: () => void;
}) {
  const { auth } = useStore();
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<SessionSearchResult[]>([]);

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return format(date, 'yyyy-MM-dd HH:mm', { locale: zhCN });
    } catch (e) {
      return dateString;
    }
  };

  // 新增：在弹窗打开时重置搜索结果
  useEffect(() => {
    if (open) {
      // 重置搜索状态
      setSearchQuery("");
      setSearchResults([]);
      setIsLoading(false);
    }
  }, [open]); // 监听 open 属性的变化

  const handleSearch = async (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!auth.isLoggedIn) return;

    setIsLoading(true);
    setSearchResults([]); // 开始新搜索时清空结果
    
    try {
      const response = await fetch(`/api/session/search?keyword=${encodeURIComponent(searchQuery)}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'X-Username': auth.username
        }
      });
      
      if (!response.ok) {
        throw new Error('搜索失败');
      }
      
      const results: SessionSearchResult[] = await response.json();
      setSearchResults(results);
    } catch (error) {
      console.error('搜索历史记录出错:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 如果没有打开，则不渲染
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 bg-opacity-50">
      <div className="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[80vh] flex flex-col">
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="text-lg font-medium">搜索历史对话</h3>
          <Button
            variant="ghost"
            size="icon"
            onClick={onClose}
          >
            <X className="w-5 h-5" />
          </Button>
        </div>
        
        {/* 搜索框 */}
        <form onSubmit={handleSearch} className="p-4 border-b">
          <div className="flex gap-2">
            <Input
              placeholder="输入关键词搜索历史对话"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="flex-1"
              autoFocus
            />
            <Button 
              type="submit"
              disabled={isLoading || !auth.isLoggedIn}
            >
              {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <SearchIcon className="w-4 h-4" />}
              <span className="ml-2">搜索</span>
            </Button>
          </div>
        </form>
        
        {/* 结果列表 */}
        <div className="flex-1 overflow-y-auto p-4">
          {!auth.isLoggedIn ? (
            <div className="text-center py-8 text-muted-foreground">
              请登录后搜索历史记录
            </div>
          ) : isLoading ? (
            <div className="flex justify-center py-8">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : searchResults.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              {searchQuery ? "没有找到相关记录" : "输入关键词后点击搜索"}
            </div>
          ) : (
            <div className="space-y-2">
              {searchResults.map(result => (
                <div 
                  key={result.session_id} 
                  className="p-3 rounded border border-gray-200 hover:bg-blue-50 cursor-pointer"
                  onClick={() => {
                    // 加载该会话
                    useStore.getState().loadSessionHistory(result.session_id);
                    onClose();
                  }}
                >
                  <div className="text-sm text-gray-800">{result.matched_message}</div>
                  <div className="text-xs text-gray-500 mt-1">
                    {formatDate(result.updated_at)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}